<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Model_album extends CI_Model
{

    /**
     * 获取我的相册信息
     *
     * @access public
     * @param  integer $uid  会员ID
     * @param  integer $page 页码
     * @return array
     */
    public function my($uid = 0, $page = 0)
    {
        $this->load->database();

        $conditions = $limit = '';
        if ($uid)
        {
             $conditions = 'WHERE `album_uid`=' . $uid;
        }

        if ($page)
        {
            $offset = 50;
            $start  = ($page - 1) * $offset;
            $limit  = "limit {$start}, {$offset}";
        }

        $uid   = intval($uid);
        $query = $this->db->query("SELECT `album_id`,`album_uid`,`album_name` FROM `tupian_album` {$conditions} ORDER BY `album_id` DESC {$limit}");
        $rows  = $query->result_array();

        return $rows;
    }

    /**
     * 保存相册信息
     *
     * @access public
     * @param  integer $uid 会员ID
     * @return array
     */
    public function save($uid)
    {
        $album_name = htmlspecialchars($this->input->post('album_name'));
        if (empty($album_name))
        {
            $response = array('error_code' => TRUE, 'msg' => '相册名称不能为空！');
            exit(json_encode($response));
        }

        $album_level = intval($this->input->post('album_level'));
        if ($album_level < 0 || $album_level > 1)
        {
            return array('error_code' => TRUE, 'msg' => '隐私设置不合法！');
        }

        $album_weibo = array();
        for ($i = 1; $i <= 4; $i++)
        {
            $album_weibo_uid = $this->get_weibo_uid($this->input->post('album_weibo_' . $i));
            if ($album_weibo_uid)
            {
                if (strlen($album_weibo_uid) <= 9) // 微号
                {
                    return array('error_code' => TRUE, 'msg' => '不支持使用微号的微博地址，请使用微博的粉丝地址试试！');
                }
                else
                {
                    $album_weibo[] = $album_weibo_uid;
                }
            }
        }

        if (empty($album_weibo))
        {
            return array('error_code' => TRUE, 'msg' => '请填写微博地址！');
        }

        // 去掉重复的UID
        $album_weibo = array_unique($album_weibo);
        $album_weibo = implode(',', $album_weibo);

        $album_id = $this->input->post('album_id');
        if ($album_id)
        {
            $data = $this->get($album_id);
            if (empty($data))
            {
                return array('error_code' => TRUE, 'msg' => '您请求的相册不存在！');
            }
            elseif ($data['album_uid'] != $uid)
            {
                return array('error_code' => TRUE, 'msg' => '您不是该相册的所有者！');
            }

            $data = array('album_id' => $album_id, 'album_name' => $album_name,
                          'album_level' => $album_level, 'album_weibo' => $album_weibo);
            $this->update($data);

            // 先删除再生成html文件
            // $this->remove_html($album_id);
            $this->generate_html($album_id);
        }
        else
        {
            $data = array('album_name'  => $album_name,  'album_uid'   => $uid,
                          'album_level' => $album_level, 'album_weibo' => $album_weibo);
            $album_id = $this->add($data);
        }

        return array('error_code' => FALSE, 'msg' => 'ok', 'album_id' => $album_id);
    }

    /**
     * 获取相册信息
     *
     * @access public
     * @param  integer $album_id 相册ID
     * @return array
     */
    public function get($album_id)
    {
        $this->load->database();

        $album_id = intval($album_id);

        $query = $this->db->query("SELECT * FROM `tupian_album` WHERE `album_id`={$album_id} LIMIT 1");
        $rows  = $query->row_array();

        return $rows;
    }

    /**
     * 添加相册信息并返回相册ID
     *
     * @access public
     * @param  array   $data 相册数据
     * @return integer
     */
    public function add($data)
    {
        $this->load->database();

        $this->db->query("INSERT INTO `tupian_album` (`album_name`,`album_uid`,`album_level`,`album_weibo`) VALUES ('{$data['album_name']}','{$data['album_uid']}','{$data['album_level']}','{$data['album_weibo']}')");

        return $this->db->insert_id();
    }

    /**
     * 更新相册信息
     *
     * @access public
     * @param  array   $data 相册数据
     * @return void
     */
    public function update($data)
    {
        $this->load->database();

        $data['album_id'] = intval($data['album_id']);

        $this->db->query("UPDATE `tupian_album` SET `album_name`='{$data['album_name']}',`album_level`='{$data['album_level']}',`album_weibo`='{$data['album_weibo']}' WHERE `album_id`={$data['album_id']}");
    }

    /**
     * 删除相册
     *
     * @access public
     * @param  integer $album_id 相册ID
     * @return void
     */
    public function remove($album_id)
    {
        $this->load->database();

        $this->db->query("DELETE FROM `tupian_album` WHERE `album_id`={$album_id}");

        $this->remove_html($album_id);
        $this->remove_image($album_id);
    }

    public function generate($album_id)
    {
        // $this->remove_html($album_id);
        $this->generate_html($album_id);
    }

    /**
     * 上传图片
     *
     * @access public
     * @param  integer $album_id 相册ID
     * @return void
     */
    public function upload($album_id, $field = 'Filedata')
    {
        // 图片上传配置
        $config = $this->config->item('picture');

        if ( ! is_dir($config['upload_path']))
        {
            mkdir($config['upload_path'], 0777);
        }
        // 按相册分目录保存
        $config['upload_path'] = $config['upload_path'] . $this->get_dir($album_id);
        if ( ! is_dir($config['upload_path']))
        {
            mkdir($config['upload_path'], 0777);
        }

        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload($field))
        {
            $response = array('error_code' => TRUE, 'msg' => $this->upload->display_errors());
        }
        else
        {
            $data = $this->upload->data();
            $data['src'] = $this->get_image_src('src', $album_id, $data['file_name']);

            $this->thumb($data['full_path']);
            $data['thumb'] = $this->get_image_src('thumb', $album_id, $data['file_name']);

            $response = array('error_code' => FALSE, 'msg' => 'ok', 'data' => $data);
        }

        return $response;
    }

    /**
     * 缩略图
     */
    public function thumb($path)
    {
        $config['image_library'] = 'gd2';
        $config['source_image'] = $path;
        $config['create_thumb'] = TRUE;
        $config['maintain_ratio'] = TRUE;
        $config['width'] = 160;
        $config['height'] = 120;

        $this->load->library('image_lib', $config);

        $this->image_lib->resize();
    }

    /**
     * 保存上传的图片
     *
     * @access public
     * @param  integer $album_id  相册ID
     * @param  string  $picture   相册图片
     * @param  string  $file_name 图片名
     * @return array
     */
    public function save_picture($album_id, $picture, $file_name)
    {
        $picture = empty($picture) ? $file_name : $picture . ',' . $file_name;

        $this->load->database();
        $this->db->query("UPDATE `tupian_album` SET `album_picture`='{$picture}' WHERE `album_id`={$album_id}");

        // 先删除再生成html文件
        // $this->remove_html($album_id);
        // $this->generate_html($album_id);

        return array('error_code' => FALSE, 'msg' => 'ok');
    }

    /**
     * 删除上传的图片
     *
     * @access public
     * @param  integer $album_id  相册ID
     * @param  string  $picture   相册图片
     * @param  string  $file_name 图片名
     * @return void
     */
    public function delete_picture($album_id, $picture, $file_name)
    {
        if (empty($picture))
        {
            return FALSE;
        }

        $picture = explode(',', $picture);
        $index = array_search($file_name, $picture);
        if ($index === FALSE)
        {
            return FALSE;
        }

        $thumb = $this->get_image_path('thumb', $album_id, $file_name);
        @unlink($thumb);
        $big = $this->get_image_path('big', $album_id, $file_name);
        @unlink($big);

        unset($picture[$index]);
        $picture = empty($picture) ? '' : implode(',', $picture);

        $this->load->database();
        $this->db->query("UPDATE `tupian_album` SET `album_picture`='{$picture}' WHERE `album_id`={$album_id}");

        return TRUE;
    }

    /**
     * 生成相册静态页面
     *
     * @access public
     * @param  integer $album_id 相册ID
     * @return void
     */
    public function generate_html($album_id)
    {
        $rows = $this->get($album_id);
        if (empty($rows))
        {
            return array('error_code' => TRUE, 'msg' => '相册不存在，无法生成静态页面！');
        }

        $dir = $this->get_dir($album_id);
        if ( ! is_dir($dir))
        {
            mkdir($dir, 0777);
        }

        $this->load->helper('file');


        $rows['album_picture'] = explode(',', $rows['album_picture']);

        $url   = $this->config->item('base_url') . '/' . $dir . '/index.html';
        $total = count($rows['album_picture']);

        list($first_weibo) = explode(',', $rows['album_weibo']);

        // 生成相册图片页
        foreach ($rows['album_picture'] as $key => $name)
        {
            $picture[$key]          = array();
            $picture[$key]['img']   = $name;
            $picture[$key]['html']  = $this->get_html($name);
            $picture[$key]['prev_html'] = 'index.html'; // 上一个图片文件
            $picture[$key]['next_html'] = 'index.html'; // 下一个图片文件

            $prev_key = $key - 1;
            if (isset($rows['album_picture'][$prev_key]))
            {
                $picture[$key]['prev_html'] = $this->get_html($rows['album_picture'][$prev_key]);
            }

            $next_key = $key + 1;
            if (isset($rows['album_picture'][$next_key]))
            {
                $picture[$key]['next_html'] = $this->get_html($rows['album_picture'][$next_key]);
            }

            $path = $dir . '/' . $picture[$key]['html'];
            $view = $this->load->view('album_template_view', array('total' => $total, 'data' => $rows, 'url' => $url, 'first' => $first_weibo, 'picture' => $picture[$key]), TRUE);
            $view = $this->zip_html($view);
            write_file($path, $view);
        }

        // 生成相册首页
        $path = $dir . '/index.html';
        $view = $this->load->view('album_template_index', array('total' => $total, 'data' => $rows, 'dir' => $dir, 'url' => $url, 'first' => $first_weibo, 'picture' => $picture), TRUE);
        $view = $this->zip_html($view);
        write_file($path, $view);
    }

    /**
     * 删除相册静态页面
     *
     * @access public
     * @param  integer $album_id 相册ID
     * @return void
     */
    public function remove_html($album_id)
    {
        // 同步删除目录以及目录下的所有文件
        $this->load->helper('file');

        $dir = $this->get_dir($album_id);
        delete_files($dir, TRUE);

        @rmdir($dir);
    }

    public function remove_image($album_id)
    {
        // 同步删除目录以及目录下的所有文件
        $this->load->helper('file');

        $dir = $this->config->item('upload_path', 'picture') . $this->get_dir($album_id);
        delete_files($dir, TRUE);

        @rmdir($dir);
    }

    public function zip_html($html)
    {
        $html = str_replace(array("\n","\t","\r\n"), '', $html);
        $html = preg_replace("~>\s+<~", "><", $html);
        $html = preg_replace("~\s\s~", '', $html);

        return $html;
    }

    /**
     * 返回相册目录名
     *
     * @access public
     * @param  integer $album_id  相册ID
     * @return string
     */
    public function get_dir($album_id)
    {
        $dir = $this->md5($album_id . $this->config->item('qq_appid'), 16);

        return $dir;
    }

    public function get_html($name)
    {
        $extension = strtolower(substr(strrchr($name, '.'), 1));

        return str_replace($extension, 'html', $name);
    }

    public function get_image_src($type, $album_id, $file_name)
    {
        if ($type == 'thumb')
        {
            $file_ext  = strtolower(substr(strrchr($file_name, '.'), 1));
            $file_name = str_replace('.' . $file_ext, '_thumb.' . $file_ext, $file_name);
            $src = $this->config->item('base_url') . '/' . $this->config->item('upload_path', 'picture') . $this->get_dir($album_id) . '/' . $file_name;
        }
        else
        {
            $src = $this->config->item('base_url') . '/' . $this->config->item('upload_path', 'picture') . $this->get_dir($album_id) . '/' . $file_name;
        }

        return $src;
    }

    public function get_image_path($type, $album_id, $file_name)
    {
        if ($type == 'thumb')
        {
            $file_ext  = strtolower(substr(strrchr($file_name, '.'), 1));
            $file_name = str_replace('.' . $file_ext, '_thumb.' . $file_ext, $file_name);
            $path = $this->config->item('upload_path', 'picture') . $this->get_dir($album_id) . '/' . $file_name;
        }
        else
        {
            $path = $this->config->item('upload_path', 'picture') . $this->get_dir($album_id) . '/' . $file_name;
        }

        return $path;
    }

    /**
     * 获取微博时间线数据
     *
     * @access public
     * @param  integer $uid 会员ID
     * @param  integer $aid 相册ID
     * @param  integer $page 页码
     * @return void
     */
    public function timeline($uid, $aid, $page)
    {
        $aid  = intval($aid);
        $rows = $this->get($aid);
        if (empty($rows) || $rows['album_uid'] != $uid)
        {
            return array('error_code' => TRUE, 'msg' => '您请求的相册不存在！');
        }

        $page     = intval($page);
        $timeline = $this->client()->timeline_batch_by_id($rows['album_weibo'], $page, 90, 2);
        if ($this->api_error($timeline))
        {
            return array('error_code' => TRUE, 'msg' => '请求微博数据失败，请稍等几分钟再试！');
        }

        return array('error_code' => FALSE, 'msg' => 'ok', 'timeline' => $timeline);
    }

    /**
     * 通过微博获取微博UID
     *
     * @access public
     * @param  string $url 微博地址
     * @return array
     */
    public function get_weibo_uid($url)
    {
        $url = trim($url);
        if (empty($url))
        {
            return FALSE;
        }

        $parse = parse_url($url);
        if (! isset($parse['path']) || empty($parse['path']))
        {
            return FALSE;
        }

        $uid = array_pop(explode('/', $parse['path']));
        if ( ! preg_match('/^[0-9]*$/', $uid))
        {
            // 通过个性化域名获取用户资料以及用户最新的一条微博
            $user = $this->client()
                         ->domain_show($uid);
            // 是否有错误
            if ($this->api_error($user))
            {
                return FALSE;
            }
            else
            {
                $uid = $user['id'];
            }
        }

        return $uid;
    }

    /**
     * Oauth实例
     *
     * @access public
     * @return SaeTOAuthV2
     */
    public function oauth()
    {
        static $oauth;

        if (empty($oauth))
        {
            require FCPATH . APPPATH . 'libraries/SaeTOAuthV2.php';
            $oauth = new SaeTOAuthV2($this->config->item('appkey'), $this->config->item('appsecret'));
        }

        return $oauth;
    }

    /**
     * Client实例
     *
     * @access public
     * @param  string  $access     访问令牌
     * @param  string  $appkey     应用令牌
     * @param  string  $appsecret  应用密钥
     * @return SaeTClientV2
     */
    public function client($access = NULL, $appkey = NULL, $appsecret = NULL)
    {
        static $client;

        if (empty($client))
        {
            $this->oauth();

            $appkey    = empty($appkey) ? $this->config->item('sina_appkey') : $appkey;
            $appsecret = empty($appsecret) ? $this->config->item('sina_appsecret') : $appsecret;

            if (empty($access))
            {
                $access = $this->config->item('sina_access');
                $access = $access[array_rand($access)];
            }

            require FCPATH . APPPATH . 'libraries/SaeTClientV2.php';
            $client = new SaeTClientV2($appkey, $appsecret, $access);
        }

        return $client;
    }

    /**
     * 根据接口返回的结果判断是否有错误
     * 如果有则返回错误信息
     *
     * @access public
     * @param  array  $result 从接口返回的结果
     * @return mixed
     */
    public function api_error(&$result)
    {
        if ( ! isset($result['error_code']))
        {
            return FALSE;
        }

        $error = '';
        foreach ($result as $key => $value)
        {
            $error .= "<p>{$key}: {$value}</p>";
        }

        return $error;
    }

    /**
     * MD5加密
     *
     * 支持返回16位的MD5加密字符串
     *
     * @access public
     * @param  string  $string 字符串
     * @param  integer $length 整数
     * @return string
     */
    public function md5($string, $length = 32)
    {
        $md5 = md5($string);

        if ($length == 16)
        {
            // 16位的MD5加密字符串
            $md5 = substr($md5, 8, $length);
        }

        return $md5;
    }
}